import axios from '../js_sdk/xtshadow-axios/axios.min'
import store from '../store'
import {
	paramsToStr,
	toast
} from './tools'


import {
	baseURL,
	suiteIds
} from '../config/app'


function checkParams(params) {
	if (typeof params != 'object') return params
	for (let key in params) {
		const value = params[key];
		if (value === null || value === undefined || value === "") {
			delete params[key];
		}
	}
	return params;
}

const service = axios.create({
	baseURL: baseURL,
	timeout: 8000,
	header: {
		'content-type': 'application/json;charset:utf-8'
	},

});

// request拦截器
service.interceptors.request.use(
	config => {
		config.data = checkParams(config.data)
		config.params = checkParams(config.params)
		if (config.method == 'GET') {
			config.url += paramsToStr(config.params)
		}
		const Store = uni.getStorageSync('token');
		//const pages = getCurrentPages()[0];
		if (Store) { //没有token就不发送token
			config.header.Authorization = 'Bearer ' + Store.token
			config.header.Cookie = 'sidebarStatus=0; Admin-Token=' + Store.token
		}
		return config
	},
	error => {
		// Do something with request error
		//console.log(error) // for debug
		Promise.reject(error)
	}
)

// response 拦截器
service.interceptors.response.use(
	async (response) => {
			//console.log(response,'response');
			return Promise.resolve(response.data)
		},
		error => {
			console.log(error, 'error');
			if (!error.response) { //超时
				uni.showToast({
					title: "网络超时，请重新尝试",
					icon: "none"
				})
			} else {
				uni.showToast({ //响应错误
					title: error.response.data.message,
					icon: "none"
				})
			}
			//console.log('err' + error) // for debug
			return Promise.reject(error)
		}
)

export default service